package net.yxsoft.controller.pc.sysmgt;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.protobuf.ByteString;
import com.jfinal.aop.Clear;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import net.yxsoft.bean.deployApp.DeployRequest;
import net.yxsoft.chainmaker.InitClient;
import net.yxsoft.controller.pc.sysmgt.common.AuthController;
import net.yxsoft.service.BlockchainManagementService;
import net.yxsoft.service.EvidenceService;
import net.yxsoft.service.OrderService;
import net.yxsoft.service.RemoteAppService;
import org.apache.commons.lang.StringUtils;
import org.chainmaker.pb.common.ChainmakerBlock;
import rapid.core.Authuser;
import rapid.core.TResult;

import java.util.*;

public class RemoteAppController extends AuthController {
    private static final RemoteAppService asr = RemoteAppService.INSTANCE;

    /**
     * 区块链存证类
    * */
    private static final EvidenceService evi = EvidenceService.me;

    /**
     * 区块链命令类
     * */
    private static final OrderService ord = OrderService.me;
    /**
     * 区块链管理类
     * */
    private static final BlockchainManagementService blo = BlockchainManagementService.me;

    /**
     * 启动远程服务
     *  cid 表单数据cid
     * */
    public void manageIndex(){
        //获取服务单元管理集合
        Integer orderSize=0;
        Integer stateSize=0;
        Integer evidenceSize=0;
        List<Record> recordList = Db.find("SELECT * FROM fn_form_data WHERE attrib_01=(SELECT id FROM fn_form WHERE code='yyfwdygl')");
        for (Record record:recordList) {
            try{
                //ATTRIB_06 合约名称  | ATTRIB_12 部署应用服务单元  |ATTRIB_35 合约分类
                Record gx = Db.findFirst("SELECT ATTRIB_06 AS contractName FROM fn_form_data WHERE attrib_01=(SELECT id FROM fn_form WHERE code='znhy') and ATTRIB_12= ? and ATTRIB_35= ? ", record.getStr("ATTRIB_03"), "共享业务");
                Record cz = Db.findFirst("SELECT ATTRIB_06 AS contractName FROM fn_form_data WHERE attrib_01=(SELECT id FROM fn_form WHERE code='znhy') and ATTRIB_12= ? and ATTRIB_35= ? ", record.getStr("ATTRIB_03"), "存证业务");
                if(gx!=null){
                     orderSize += ord.getOrderSize(InitClient.chainClient, gx.getStr("contractName"));//上链指令数据
                     stateSize += ord.getStateSize(InitClient.chainClient, gx.getStr("contractName"));//上链状态数据
                }
                if(cz!=null){
                     evidenceSize += evi.getEvidenceSize(InitClient.chainClient, cz.getStr("contractName"));//存证数量
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        try {
            String chainId = PropKit.get("blockchain.chainId");
            JSONObject chainBasicInfo = blo.getChainBasicInfo(InitClient.chainClient, chainId);
            set("blockHeight",chainBasicInfo.getInt("BlockHeight"));
            set("transactionNum",chainBasicInfo.getInt("TransactionNum"));
            //获取各类指标时间
            Map<String, String> latestTime = blo.getLatestTime(InitClient.chainClient);
            if(latestTime.size()>0){
                set("orderStamp",latestTime.get("orderStamp"));
                set("stateStamp",latestTime.get("stateStamp"));
                set("evidenceStamp",latestTime.get("evidenceStamp"));
                set("blockStamp",latestTime.get("blockStamp"));
                set("transStamp",latestTime.get("transStamp"));

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        set("orderSize",orderSize);
        set("stateSize",stateSize);
        set("evidenceSize",evidenceSize);
        render("index.html");
    }

    /**
     * 应用服务单元管理页面
     *  cid 表单数据cid
     * */
    public void indexNode(){
        Authuser loginUser = getLoginUser();
        String groupNames = loginUser.get("GROUP_NAMES").toString();
        String[] groupNameArr = groupNames.split(",");
        StringJoiner groupJoiner = new StringJoiner(",");
        for (Object groupName:groupNameArr) {
            groupJoiner.add("?");
        }
        List roles = (List) loginUser.get("ROLES");
        StringJoiner roleJoiner = new StringJoiner(",");
        for (Object role:roles) {
            roleJoiner.add("?");
        }
        //返回用户角色权限
        if(roleJoiner.length()>0){
            List<Record> records = Db.find("SELECT name,code FROM ts_role WHERE  code in( "+roleJoiner.toString()+" )", roles.toArray());
            set("roles",records);
        }

        //获取服务单元管理集合  -- 根据用户的机构显示相应的数据
        List<Record> recordList=new ArrayList<>();
        if(StringUtils.isBlank(groupNames) || "总部".equals(groupNames)){
            recordList = Db.find("SELECT * FROM fn_form_data WHERE attrib_01=(SELECT id FROM fn_form WHERE code='yyfwdygl')");
        }else{
            recordList = Db.find("SELECT * FROM fn_form_data WHERE attrib_01=(SELECT id FROM fn_form WHERE code='yyfwdygl') and attrib_03 in( "+groupJoiner.toString()+" )",groupNameArr);
        }
        //recordList = Db.find("SELECT * FROM fn_form_data WHERE attrib_01=(SELECT id FROM fn_form WHERE code='yyfwdygl')");
        for (Record record:recordList) {
            try{
                //ATTRIB_06 合约名称  | ATTRIB_12 部署应用服务单元  |ATTRIB_35 合约分类
                Record gx = Db.findFirst("SELECT ATTRIB_06 AS contractName FROM fn_form_data WHERE attrib_01=(SELECT id FROM fn_form WHERE code='znhy') and ATTRIB_12= ? and ATTRIB_35= ? ", record.getStr("ATTRIB_03"), "共享业务");
                Record cz = Db.findFirst("SELECT ATTRIB_06 AS contractName FROM fn_form_data WHERE attrib_01=(SELECT id FROM fn_form WHERE code='znhy') and ATTRIB_12= ? and ATTRIB_35= ? ", record.getStr("ATTRIB_03"), "存证业务");
                record.set("evidenceSize",null);
                record.set("orderSize",null);
                record.set("stateSize",null);
                if(gx!=null){
                    Integer orderSize = ord.getOrderSize(InitClient.chainClient, gx.getStr("contractName"));//上链指令数据
                    Integer stateSize = ord.getStateSize(InitClient.chainClient, gx.getStr("contractName"));//上链状态数据
                    record.set("orderSize",orderSize);
                    record.set("stateSize",stateSize);
                }
                if(cz!=null){
                    Integer evidenceSize = evi.getEvidenceSize(InitClient.chainClient, cz.getStr("contractName"));//存证数量
                    record.set("evidenceSize",evidenceSize);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        set("recordList",recordList);
        render("indexNode.html");
    }


    /**
     * 应用单元管理页面--新
     * */
    public void unitmanage(){
        Authuser loginUser = getLoginUser();
        String groupNames = loginUser.get("GROUP_NAMES").toString();
        String[] groupNameArr = groupNames.split(",");
        StringJoiner groupJoiner = new StringJoiner(",");
        for (Object groupName:groupNameArr) {
            groupJoiner.add("?");
        }
        List roles = (List) loginUser.get("ROLES");
        StringJoiner roleJoiner = new StringJoiner(",");
        for (Object role:roles) {
            roleJoiner.add("?");
        }
        //返回用户角色权限
        if(roleJoiner.length()>0){
            List<Record> records = Db.find("SELECT name,code FROM ts_role WHERE  code in( "+roleJoiner.toString()+" )", roles.toArray());
            set("roles",records);
        }

        //获取服务单元管理集合  -- 根据用户的机构显示相应的数据
        List<Record> recordList=new ArrayList<>();
        if(StringUtils.isBlank(groupNames) || "总部".equals(groupNames)){
            recordList = Db.find("SELECT * FROM fn_form_data WHERE attrib_01=(SELECT id FROM fn_form WHERE code='yyfwdygl')");
        }else{
            recordList = Db.find("SELECT * FROM fn_form_data WHERE attrib_01=(SELECT id FROM fn_form WHERE code='yyfwdygl') and attrib_03 in( "+groupJoiner.toString()+" )",groupNameArr);
        }
        //recordList = Db.find("SELECT * FROM fn_form_data WHERE attrib_01=(SELECT id FROM fn_form WHERE code='yyfwdygl')");
        for (Record record:recordList) {
            try{
                //ATTRIB_06 合约名称  | ATTRIB_12 部署应用服务单元  |ATTRIB_35 合约分类
                Record gx = Db.findFirst("SELECT ATTRIB_06 AS contractName FROM fn_form_data WHERE attrib_01=(SELECT id FROM fn_form WHERE code='znhy') and ATTRIB_12= ? and ATTRIB_35= ? ", record.getStr("ATTRIB_03"), "共享业务");
                Record cz = Db.findFirst("SELECT ATTRIB_06 AS contractName FROM fn_form_data WHERE attrib_01=(SELECT id FROM fn_form WHERE code='znhy') and ATTRIB_12= ? and ATTRIB_35= ? ", record.getStr("ATTRIB_03"), "存证业务");
                record.set("evidenceSize",null);
                record.set("orderSize",null);
                record.set("stateSize",null);
                if(gx!=null){
                    Integer orderSize = ord.getOrderSize(InitClient.chainClient, gx.getStr("contractName"));//上链指令数据
                    Integer stateSize = ord.getStateSize(InitClient.chainClient, gx.getStr("contractName"));//上链状态数据
                    record.set("orderSize",orderSize);
                    record.set("stateSize",stateSize);
                }
                if(cz!=null){
                    Integer evidenceSize = evi.getEvidenceSize(InitClient.chainClient, cz.getStr("contractName"));//存证数量
                    record.set("evidenceSize",evidenceSize);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        set("recordList",recordList);
        render("yingyong.html");
    }

    /**
     * 查看单元服务部署应用页面--新页面
     * */
    public void bushu(){
        render("bushu.html");
    }

    /**
     * 部署应用页面开始部署--新页面
     * */
    @Clear
    public void deployApp(){
        //将post请求中body的数据映射到DeployRequest实体类上
        DeployRequest deploy = JSON.parseObject(getRawData(), DeployRequest.class);
        Authuser loginUser = getLoginUser();//登入用户
        renderJson(asr.deployApp(deploy,loginUser));
    }

    /**
     * 部署TpServer项目--新页面
     * */
    @Clear
    public void deployTpServer() throws Exception {
        //将post请求中body的数据映射到DeployRequest实体类上
        DeployRequest deploy = JSON.parseObject(getRawData(), DeployRequest.class);
        asr.deployTpServer(deploy);
        renderJson();
    }
    /**
     * 部署DataBase项目--新页面
     * */
    @Clear
    public void deployDataBase() throws Exception {
        //将post请求中body的数据映射到DeployRequest实体类上
        DeployRequest deploy = JSON.parseObject(getRawData(), DeployRequest.class);
        asr.deployDataBase(deploy);
        renderJson();
    }

    /**
     * 区块链接口
     * */
    @Clear
    public void chainList(){
        List<Record> records = Db.find("SELECT chain_id,chain_name FROM cmb_chain");
        renderJson(records);
    }

    /**
     * 区块链组织集合接口
     * */
    @Clear
    public void chainOrgList(){
        String chainId = getPara("chain_id");
        List<Record> records = Db.find("SELECT * FROM cmb_chain_org WHERE chain_id=?",chainId);
        renderJson(records);
    }

    /**
     * 区块链节点集合接口
     * */
    @Clear
    public void chainNodeList(){
        String chainId = getPara("chain_id");
        String orgId = getPara("org_id");
        List<Record> records = Db.find("SELECT * FROM `cmb_chain_org_node` WHERE chain_id =?  AND  org_id=?",chainId,orgId);
        renderJson(records);
    }

    /**
     * 区块链组织用户集合接口
     * */
    @Clear
    public void chainOrgUserList(){
        String orgId = getPara("org_id");
        List<Record> records = Db.find("SELECT DISTINCT cert_user_name as orguser FROM cmb_cert WHERE org_id=? AND cert_user_name != '' ",orgId);
        renderJson(records);
    }

    /**
     * 区块链组织用户集合接口
     * */
    @Clear
    public void shareAndEvidenceList(){
        String chainId = getPara("chain_id");
        List<Record> records = Db.find("SELECT * FROM cmb_contract WHERE chain_id = ? ",chainId);
        renderJson(records);
    }

    /**
     * 存证账号授权----新页面
     * contractName 合约名称
     * cid  用户Id
     * category 授权类型
     * */
    @Clear
    public void evidenceAuthorize(){
        String contractName = getPara("contractName");
        String orgId = getPara("org_id");
        String orguser = getPara("orguser");
        Boolean b=null;
        try {
            b = evi.transferOwnerTwo(InitClient.chainClient,orgId,orguser, contractName);
        } catch (Exception e) {
            b= false;
            e.printStackTrace();
        }
        if(b){
            renderJson(Ret.ok());
        }else {
            renderJson(Ret.fail());
        }
    }

    /**
     * 共享账号授权----新页面
     * contractName 合约名称
     * cid  用户Id
     * category 授权类型
     * */
    @Clear
    public void shareAuthorize(){
        String contractName = getPara("contractName");
        String orgId = getPara("org_id");
        String orguser = getPara("orguser");
        String category = getPara("category");
        Boolean b=null;
        try {
            b = ord.authorizeTwo(InitClient.chainClient, contractName, orgId,orguser, category);
        } catch (Exception e) {
            b= false;
            e.printStackTrace();
        }
        if(b){
            renderJson(Ret.ok());
        }else {
            renderJson(Ret.fail());
        }
    }


    /**
     * 查看单元服务相关状态--新页面
     * Cid
    * */
    @Clear
    public void selectUnitStatusByCid(){
        String cid = get("cid");
        Map map = asr.selectUnitStatusByCid(cid);
        renderJson(map);
    }

    /**
     * 切换应用服务单元启停状态--新页面
     * Cid
     * */
    public void switchAppStatusByCid(){
        String cid = get("cid");
        boolean status = getBoolean("status");//状态
        Map map = asr.switchAppStatusByCid(cid,status);
        renderJson(map);
    }

    /**
     * 切换数据任务状态启停--新页面
     * Cid
     * */
    public void switchDataStatusByCid(){
        String cid = get("cid");
        boolean status = getBoolean("status");//状态
        JsonNode jsonNode = asr.switchDataStatusByCid(cid, status);
        renderJson(jsonNode.toString());
    }

    /**
     * 切换文件任务状态启停--新页面
     * Cid
     * */
    public void switchFileStatusByCid(){
        String cid = get("cid");
        boolean status = getBoolean("status");//状态
        JsonNode jsonNode = asr.switchFileStatusByCid(cid, status);
        renderJson(jsonNode.toString());
    }


    /**
     * 应用服务单元管理--运行管理页面
     *  cid 表单数据cid
     * */
    public void unitManagement(){
        String cid = get("cid");
        set("cid",cid);
        Record record = Db.findFirst("select * from fn_form_data where conflict_id= ?",cid);
        try{
            //ATTRIB_06 合约名称  | ATTRIB_12 部署应用服务单元  |ATTRIB_35 合约分类
            Record gx = Db.findFirst("SELECT ATTRIB_06 AS contractName FROM fn_form_data WHERE attrib_01=(SELECT id FROM fn_form WHERE code='znhy') and ATTRIB_12= ? and ATTRIB_35= ? ", record.getStr("ATTRIB_03"), "共享业务");
            Record cz = Db.findFirst("SELECT ATTRIB_06 AS contractName FROM fn_form_data WHERE attrib_01=(SELECT id FROM fn_form WHERE code='znhy') and ATTRIB_12= ? and ATTRIB_35= ? ", record.getStr("ATTRIB_03"), "存证业务");
            record.set("evidenceSize",null);
            record.set("orderSize",null);
            record.set("stateSize",null);
            if(gx!=null){
                Integer orderSize = ord.getOrderSize(InitClient.chainClient, gx.getStr("contractName"));//上链指令数据
                Integer stateSize = ord.getStateSize(InitClient.chainClient, gx.getStr("contractName"));//上链状态数据
                record.set("orderSize",orderSize);
                record.set("stateSize",stateSize);
            }
            if(cz!=null){
                Integer evidenceSize = evi.getEvidenceSize(InitClient.chainClient, cz.getStr("contractName"));//存证数量
                record.set("evidenceSize",evidenceSize);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        set("record",record);
        List<Record> configList = Db.find("SELECT * FROM fn_form_data WHERE row_id= ? and attrib_01=(SELECT id FROM fn_form WHERE code='fwpzbggl')", cid);
        set("configList",configList);//服务与配置变更管理列表
        render("unitManagement.html");
    }

    /**
     * 应用服务单元管理--智能合约管理
     * */
    @Clear
    public void smartContracts(){
        String cid = get("cid");
        Record record = Db.findFirst("select * from fn_form_data where conflict_id= ?",cid);
        if(record!=null){
            //ATTRIB_06 合约名称  | ATTRIB_12 部署应用服务单元
            List<Record> recordList = Db.find("SELECT * FROM fn_form_data WHERE attrib_01=(SELECT id FROM fn_form WHERE code='znhy') and ATTRIB_12= ?", record.getStr("ATTRIB_03"));
            set("recordList",recordList);//智能合约返回
            set("record",record);//引用服务单元动态表单
        }
        //返回角色权限功能
        Authuser loginUser = getLoginUser();
        List roles = (List) loginUser.get("ROLES");
        StringJoiner roleJoiner = new StringJoiner(",");
        for (Object role:roles) {
            roleJoiner.add("?");
        }
        //返回用户角色权限
        if(roleJoiner.length()>0){
            List<Record> records = Db.find("SELECT name,code FROM ts_role WHERE  code in( "+roleJoiner.toString()+" )", roles.toArray());
            set("roles",records);
        }
        render("smartContracts.html");
    }

    /**
     * 上链存证数据查询检索
     * */
    @Clear
    public void selectBlockEvidenceData(){
        Page<Record> list=new Page<>();
        String rawData = getRawData();
        if(StringUtils.isNotBlank(rawData)){
            Map<String,Object> map = JSON.parseObject(rawData, Map.class);
            //czsjcxhss -- 上链存证数据查询检索
            list = asr.selectBlockDataList("czsjcxhss", map);
        }
        renderJson(list);
    }

    /**
     * 上链共享数据查询检索接口
     * */
    @Clear
    public void selectBlockShareData(){
        Page<Record> list=new Page<>();
        String rawData = getRawData();
        if(StringUtils.isNotBlank(rawData)){
            Map<String,Object> map = JSON.parseObject(rawData, Map.class);
            //yyfwslxx -- 上链共享数据查询检索
            list = asr.selectBlockDataList("yyfwslxx", map);
        }
        renderJson(list);
    }

    /**
     * 上链共享数据更新
     * */
    @Clear
    public void refreshBlockShareData(){
        String contractName = getPara("contractName");
        try {
            ord.getAllStatesToDb(InitClient.chainClient,contractName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        renderJson(Ret.ok());
    }

    /**
     * 上链存证数据更新
     * */
    @Clear
    public void refreshBlockEvidenceData(){
        String contractName = getPara("contractName");
        try {
            evi.getAllEvidencesToDb(InitClient.chainClient,contractName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        renderJson(Ret.ok());
    }

    /**
     * 获取账号授权列表
     * unitName 单元名称
     * */
    @Clear
    public void getAuthorizeList(){
        //单元名称
        String unitName = getPara("unitName");
        //qklzh -- 区块链账号动态表单
        List<Record> records = Db.find("SELECT conflict_id,attrib_03 FROM fn_form_data WHERE attrib_01=(SELECT id FROM fn_form WHERE code='qklzh') and ATTRIB_10= ?", unitName);
        renderJson(records);
    }

    /**
     * 共享账号授权
     * contractName 合约名称
     * cid  用户Id
     * category 授权类型
     * */
    @Clear
    public void setEvidenceAuthorize(){
        String contractName = getPara("contractName");
        String cid = getPara("cid");
        Boolean b=null;
        try {
             b = evi.transferOwner(InitClient.chainClient, contractName, cid);
        } catch (Exception e) {
            b= false;
            e.printStackTrace();
        }
        if(b){
            renderJson(Ret.ok());
        }else {
            renderJson(Ret.fail());
        }
    }

    /**
     * 共享账号授权
     * contractName 合约名称
     * cid  用户Id
     * category 授权类型
     * */
    @Clear
    public void setShareAuthorize(){
        String contractName = getPara("contractName");
        String cid = getPara("cid");
        String category = getPara("category");
        Boolean b=null;
        try {
            b = ord.authorize(InitClient.chainClient, contractName, cid, category);
        } catch (Exception e) {
            b= false;
            e.printStackTrace();
        }
        if(b){
            renderJson(Ret.ok());
        }else {
            renderJson(Ret.fail());
        }
    }


    /**
     * 动态表单数据查询--通用数据查询
     * cid 通用Id
     * */
    @Clear
    public void selectFormDataByCid(){
        String cid = getPara("cid");
        Record record = Db.findFirst("SELECT * FROM fn_form_data WHERE conflict_id= ?", cid);
        List dataList = new ArrayList<>();
        if (record==null){
            renderJson(dataList);
            return;
        }
        List<Record> fieldList = Db.find("SELECT * FROM fn_form_field where form_id= ? and state='1'  order by sort desc", record.getStr("attrib_01"));
        for (Record field:fieldList) {
            Map map = new HashMap<>();
            map.put("name",field.getStr("title"));
            map.put("value",record.getStr(field.getStr("field")));
            map.put("field",field.getStr("field"));
            dataList.add(map);
        }
        renderJson(dataList);
    }

    /**
     * 共享详情页面通过Cid
     * cid 通用Id
     * */
    @Clear
    public void shareDetailsByCid(){
        String cid = getPara("cid");
        Record record = Db.findFirst("SELECT * FROM fn_form_data WHERE conflict_id= ?", cid);
        if(record!=null){
            //ATTRIB_08 --合约说明
            Record hysm = Db.findFirst("SELECT ATTRIB_08 FROM fn_form_data " +
                    "WHERE attrib_01=(SELECT id FROM fn_form WHERE code='znhy')" +
                    " AND ATTRIB_06 =? ", record.getStr("attrib_41"));
            if(hysm!=null){
                record.set("hysm",hysm.get("ATTRIB_08"));
            }
            //判断发送方区块高度是否为空
            if(StringUtils.isNotBlank(record.getStr("attrib_44"))){
                long BlockHeight = Long.parseLong(record.getStr("attrib_44"));
                ChainmakerBlock.BlockInfo blockInfo = blo.getBlockByHeight(InitClient.chainClient, BlockHeight);
                ByteString blockHash = blockInfo.getBlock().getHeader().getBlockHash();
                String blockHashString = javax.xml.bind.DatatypeConverter.printHexBinary(blockHash.toByteArray()).toLowerCase();
                record.set("fsblockhash",blockHashString);
            }
            //判断接收方区块高度是否为空
            if(StringUtils.isNotBlank(record.getStr("attrib_47"))){
                long BlockHeight = Long.parseLong(record.getStr("attrib_47"));
                ChainmakerBlock.BlockInfo blockInfo = blo.getBlockByHeight(InitClient.chainClient, BlockHeight);
                ByteString blockHash = blockInfo.getBlock().getHeader().getBlockHash();
                String blockHashString = javax.xml.bind.DatatypeConverter.printHexBinary(blockHash.toByteArray()).toLowerCase();
                record.set("jsblockhash",blockHashString);
            }
        }
        renderJson(record);
    }

    /**
     * 存证详情页面通过Cid
     * cid 通用Id
     * */
    @Clear
    public void evidenceDetailsByCid(){
        String cid = getPara("cid");
        Record record = Db.findFirst("SELECT * FROM fn_form_data WHERE conflict_id= ?", cid);
        if(record!=null){
            //ATTRIB_08 --合约说明
            Record hysm = Db.findFirst("SELECT ATTRIB_08 FROM fn_form_data " +
                    "WHERE attrib_01=(SELECT id FROM fn_form WHERE code='znhy')" +
                    " AND ATTRIB_06 =? ", record.getStr("attrib_41"));
            if(hysm!=null){
                record.set("hysm",hysm.get("ATTRIB_08"));
            }
            //判断区块高度是否为空
            if(StringUtils.isNotBlank(record.getStr("attrib_44"))){
                long BlockHeight = Long.parseLong(record.getStr("attrib_44"));
                ChainmakerBlock.BlockInfo blockInfo = blo.getBlockByHeight(InitClient.chainClient, BlockHeight);
                ByteString blockHash = blockInfo.getBlock().getHeader().getBlockHash();
                String blockHashString = javax.xml.bind.DatatypeConverter.printHexBinary(blockHash.toByteArray()).toLowerCase();
                record.set("blockhash",blockHashString);
            }
        }
        renderJson(record);
    }

    /**
     * 动态表单数据新增查询字段属性
     * code 动态表单code值
     * */
    @Clear
    public void  selectFormDataFieldByCode(){
        String code = getPara("code");
        Record record = Db.findFirst("SELECT id FROM fn_form WHERE code=?", code);
        List<Record> fieldList = Db.find("SELECT * FROM fn_form_field where form_id= ? and state='1'  order by sort desc", record.getStr("id"));
        for (Record field:fieldList) {
           if(StringUtils.isNotBlank(field.getStr("code_name"))){
               List<Record> records = Db.find("SELECT codeid,codename FROM ts_code WHERE parentname=? ",field.getStr("code_name"));
               field.set("list",records);
           }
        }
        renderJson(fieldList);
    }


    /**
     * 动态表单数据新增
     * code 动态表单code值
     * */
    @Clear
    public void  InsertFormData(){
        String rawData = getRawData();
        Map<String,Object> map = JSON.parseObject(rawData, Map.class);
        Authuser loginUser = getLoginUser();
        TResult tResult = asr.InsertFormData(loginUser,map);
        renderJson(tResult);
    }

    /**
     * 应用服务单元管理--新增数据方法
     *  cid 表单数据cid
     * */
    @Clear
    public void InsertUnit(){
        String rawData = getRawData();
        Map<String,Object> map = JSON.parseObject(rawData, Map.class);
        Authuser loginUser = getLoginUser();
        TResult tResult = asr.insertUnit(loginUser,map);
        renderJson(tResult);
    }

    /**
     * 服务与配置变更管理--新增数据方法
     *  cid 表单数据cid
     * */
    @Clear
    public void InsertServiceConfig(){
        String rawData = getRawData();
        Map<String,Object> map = JSON.parseObject(rawData, Map.class);
        Authuser loginUser = getLoginUser();
        TResult tResult = asr.insertServiceConfig(loginUser,map);
        renderJson(tResult);
    }

    /**
     * 应用服务单元管理--通用修改数据方法
     *  cid 表单数据cid
     * */
    @Clear
    public void updatePublicMethods(){
        String rawData = getRawData();
        Map<String,Object> map = JSON.parseObject(rawData, Map.class);
        Authuser loginUser = getLoginUser();
        TResult tResult = asr.updatePublicMethods(loginUser,map);
        renderJson(tResult);
    }

    /**
     * 应用服务单元管理--通用删除数据方法
     *  cid 表单数据cid
     * */
    @Clear
    public void deletePublicMethods(){
        String cid = getPara("cid");
        renderJson(asr.deletePublicMethods(cid));
    }

    /**
     * 查询单元站点区块各类数据信息
     *  name  站点名称
     * */
    @Clear
    public void selectUnitBlockData(){
        String name = getPara("name");
        renderJson(asr.selectUnitBlockData(name));
    }


    /**
     * 启动远程服务
     *  cid 表单数据cid
     * */
    public void startRemoteApp(){
        String cid = getPara("cid");
        renderJson(asr.startRemoteApp(cid));
    }

    /**
     * 停止远程服务
     *  cid 表单数据cid
     * */
    public void stopRemoteApp(){
        String cid = getPara("cid");
        renderJson(asr.stopRemoteApp(cid));
    }

    /**
     * 部署服务脚本
     *  cid 表单数据cid
     * */
    public void uploadToRemote(){
        String cid = getPara("cid");
        renderJson(asr.uploadToRemote(cid));
    }

    /**
     * 更新服务
     *  cid 表单数据cid
     * */
    public void updateRemoteApp(){
        String cid = getPara("cid");
        renderJson(asr.updateRemoteApp(cid));
    }

    /**
     * 服务与配置变更管理 切换状态
     *  cid 表单数据cid
     * */
    @Clear
    public void mocSwitchState(){
        String cid = getPara("cid");
        renderJson(asr.mocSwitchState(cid).toString());
    }


    /**
     * 服务与配置变更管理 操作执行
     *  cid 表单数据cid
     * */
    public void mocExec(){
        String cid = getPara("cid");
        JsonNode jsonNode = asr.mocExec(cid);
        renderJson(jsonNode.toString());
    }

}
